import { IMTableType } from "@/types/table";
import { isResetOldPassword } from "@home/store";
import { tmp_proxy, fetchList, showDrawer, showModal } from ".";
import {
  channelOptions,
  dicts,
  drawerChannelMap,
  lockTypeOptions,
  popularOptions,
  scoreOptions,
  userTypeMap,
  vipOptions,
} from "./dict";
import { fetchDataById, fetchDicts, getStarSign, toTimeStamp } from "./utils";
import { modalFormState, modalTitle } from "./modal";
import { drawerTitle } from "./drawer";
import { tableLoading } from "./table";
import { DrawerFormStateType } from "./type";
export const center = reactive<any>({ lat: 22.543099, lng: 114.057868 });
export const mapRef = ref<any>(null);
export const tableActiveKey = ref(0);
export let analysisUsers = reactive<any>([]);
export const operateType = ref<string>("");
export const clickPointType = ref(0);
export const drawerFormState = reactive<any>({});
export const resetFormState = (formState) => {
  const defaultFormState = reactive<DrawerFormStateType>({
    country_code: undefined,
    country: undefined,
    position: undefined,
    lat: undefined,
    long: undefined,
    avatar: undefined,
    nickname: undefined,
    height: undefined,
    weight: undefined,
    sex: 1,
    social_account_type: "whatsapp",
    social_account: undefined,
    mobile_area: undefined,
    mobile_number: undefined,
    birthday: undefined,
    origin: undefined,
    channel_id: undefined,
    merchant_uid: undefined,
    account_type: 2,
    is_lock: 0,
    vip_level: undefined,
    popular_level: undefined,
    score_level: undefined,
    uid: undefined,
    verify_video: undefined,
    verifyFileid: undefined,
    bio: undefined,
    cup: undefined,
    password: undefined,
    password_confirmation: undefined,
    tag_ids: [],
    accountSystemTag: [],
    accountTag: [],
    systemIds: [],
    auth: 1,
    images: [],
    content: undefined,
    province: undefined,
    city: undefined,
    dynamicIds: [],
    dynamics: [],
    userDynamics: [],
    video: undefined,
    partyNum: undefined,
    location: undefined,
    position_country_code: "",
    content_position_country_code: "",
    intention: [],
    month_income: undefined,
    occupation_id: undefined,
    occupation_post: undefined,
    real_person_status: undefined,
    constellation: undefined,
    can_provide: undefined,
    hair_color: undefined,
    eye_color: undefined,
    skin_color: undefined,
    punch: undefined,
    tattoo: undefined,
    race: undefined,
    smoke: undefined,
    drink: undefined,
    educational: undefined,
    account_picture: Array(4).fill(""),
  });
  Object.keys(defaultFormState).forEach((key) => {
    if (key != "mobile_area") formState[key] = defaultFormState[key];
  });
};
resetFormState(drawerFormState);
export const set_formState = async (
  type: string,
  formInline: any,
  data: any
) => {
  operateType.value = type;
  resetFormState(formInline);
  switch (type) {
    case "add":
      drawerTitle.value = $t("base.addUser");
      formInline.birthday = $dayjs(
        getLastYear(18).getTime() - 1 * 24 * 60 * 60 * 1000
      );
      const start_sign = getStarSign(formInline.birthday);
      formInline.constellation = start_sign;
      showDrawer();
      break;
    case "update":
      drawerTitle.value = $t("base.editUser");
      tableLoading.value = true;
      await fetchDataById(data);
      const res: any = await fetchDicts(ref({}), {
        userId: data.uid,
      });
      const {
        accountInfo = {},
        account = {},
        accountTag = [],
        accountSystemTag = [],
        userDynamics = [],
      } = res;
      formInline.tag_ids = accountTag?.map((item: any) => item.tag_id) ?? [];
      formInline.systemIds =
        accountSystemTag?.map((item: any) => item.tag_id) ?? [];
      formInline.userDynamics =
        userDynamics?.map((item: any) => {
          if (!isEmptyType(item.created_at))
            item.created_at = toTimeStamp(item.created_at);
          return item;
        }) ?? [];
      formInline.country_code = accountInfo.country_code;
      formInline.country = accountInfo.country;
      formInline.location = accountInfo.position;
      formInline.lat = accountInfo.lat;
      formInline.long = accountInfo.long;
      formInline.avatar = accountInfo.avatar;
      formInline.nickname = accountInfo.nickname;
      formInline.height = accountInfo.height;
      formInline.weight = accountInfo.weight;
      formInline.sex = accountInfo.sex;
      formInline.social_account_type = accountInfo.social_account_type;
      formInline.social_account = accountInfo.social_account;
      formInline.verify_video = accountInfo.verify_video;
      formInline.bio = accountInfo.bio;
      formInline.cup = accountInfo.cup;
      formInline.mobile_area = accountInfo.mobile_area;
      formInline.mobile_number = accountInfo.mobile_number;
      formInline.origin = account.origin;
      formInline.channel_id = account.channel_id;
      formInline.merchant_uid = account.merchant_uid;
      formInline.account_type = account.account_type;
      formInline.is_lock = account.is_lock;
      formInline.vip_level = account.vip_level;
      formInline.popular_level = account.popular_level;
      formInline.score_level = account.score_level;
      formInline.uid = account.uid;
      formInline.birthday = accountInfo?.birthday
        ? $dayjs(accountInfo.birthday)
        : $dayjs(getLastYear(18).getTime() - 1 * 24 * 60 * 60 * 1000);
      formInline.constellation =
        formInline?.account_type === 1 && isEmptyType(formInline.constellation)
          ? getStarSign(formInline.birthday)
          : formInline.constellation;
      clearObjectZeroValue({
        target: formInline,
        targetKeys: [
          "height",
          "weight",
          "channel_id",
          "merchant_uid",
          "vip_level",
          "popular_level",
          "score_level",
        ],
      });
      if (!isEmptyType(formInline.merchant_uid))
        drawerChannelMap.value = dicts.value.channel.filter(
          ({ merchant_uid }: any) => merchant_uid === formInline.merchant_uid
        );
      formInline.accountSystemTag =
        accountSystemTag.map((item: any) => item.tag_id) ?? [];
      formInline.intention =
        data?.intention?.split?.(",")?.map?.((id) => +id) ?? [];
      formInline.occupation_post = data.occupation_post;
      formInline.month_income =
        data.month_income != 0 ? data.month_income : undefined;
      formInline.dynamicIds = [];
      tableLoading.value = false;
      showDrawer();
      break;
    case "view":
      isDisplay.value = true;
      drawerTitle.value = $t("base.userDetail");
      await fetchDataById(data);
      showDrawer();
      break;
    case "update->status":
      tmp_proxy.$confirm({
        icon: null,
        title: () => <>{$t("base.userStatusEdit")}</>,
        closable: true,
        maskClosable: true,
        style: {
          top: "30%",
        },
        content: (
          <>
            {data.is_lock === 0
              ? !isEmptyType(data.nickname)
                ? `${$t("user2")}"${data.nickname}"${$t("user0")}`
                : `${$t("user3")}"${data.uid}"${$t("user0")}`
              : !isEmptyType(data.nickname)
              ? `${$t("user2")}"${data.nickname}"${$t("user1")}`
              : `${$t("user3")}"${data.uid}"${$t("user1")}`}
          </>
        ),
        onOk: async () => {
          await userApi.updateStatus({
            userId: data.uid,
          });
          message.success($t("base.updateSucess"));
          fetchList();
        },
      });
      break;
    case "update->password":
      modalTitle.value = $t("base.changePsd");
      clearObjAttr(modalFormState);
      Object.keys(modalFormState)?.forEach(
        (key: any) => (modalFormState[key] = data[key] ?? modalFormState[key])
      );
      initObjAttr(modalInputValidators, createArray(false, 2));
      showModal();
      break;
    case "update->dispense":
      const formState = defaultModalFormState[3];
      clearObjAttr(formState);
      formState.userId = data.uid;
      defaultModalVisible[3].value = true;
      analysisUsers.length = 0;
      const fetchDispense = async () => {
        const res = await userApi.queryDispense({
          page: 1,
          page_size: 10000,
          userId: data.uid,
        });
        formState.originUser = res?.data?.originUser ?? "";
        res?.data?.analysisUsers?.forEach(
          (item: any, index: string | number) => {
            analysisUsers[index] = {
              label: item.username,
              value: item.id,
            };
          }
        ) ?? [];
      };
      fetchDispense();
      break;
  }
};
export const defaultModalLoading = toRefs(
  reactive<Boolean[]>(Array(5).fill(false))
);
export const defaultModalVisible = toRefs(
  reactive<Boolean[]>(Array(5).fill(false))
);

export const publish_time = ref($dayjs(getTimeByZone(new Date())));
export const defaultModalFormState = reactive<any>([
  // 选择标签
  {
    uid: undefined,
    tag_ids: [],
    systemIds: [],
  },
  // 发布动态
  {
    uid: undefined,
    content: undefined,
    fileList: [],
    images: [],
    location: undefined,
    auth: 1,
    video: undefined,
    videoFileid: undefined,
    content_position_country_code: "",
    created_at: undefined,
  },
  // 客户位置
  {
    location: undefined,
    searchKey: undefined,
    content_position_country_code: "",
  },
  // 客户分配
  {
    userId: undefined,
    originUser: undefined,
    targetId: undefined,
  },
  // 开通会员
  {
    userId: undefined,
    member_type: undefined,
  },
]);
export const drawerActiveKey = ref<any>(0); // 真人和机器人之间切换
export const defaultSearchList = reactive<any>([
  [
    {
      label: getProxyT("table0"),
      type: "input",
      model: "user",
      allowClear: true,
      placeholder: getProxyT("placeholder58"),
      searchClass: "search-item-width-250",
      maxlength: 20,
    },
    {
      label: getProxyT("table105"),
      type: "input",
      model: "merchant_user",
      allowClear: true,
      placeholder: getProxyT("placeholder4"),
      maxlength: 20,
    },
    {
      label: getProxyT("table13"),
      type: "select",
      model: "channel_id",
      placeholder: getProxyT("placeholder59"),
      searchClass: "search-item-width-150",
      options: channelOptions,
      allowClear: true,
    },
    {
      label: getProxyT("table18"),
      showTime: { format: "HH:mm:ss" },
      type: "rangePicker",
      model: "start_end",
      placeholder: computed(() => [$t("base.startTime"), $t("base.endTime")]),
      format: "YYYY-MM-DD HH:mm:ss",
    },
    {
      label: getProxyT("table5"),
      type: "select",
      model: "vip_level",
      placeholder: getProxyT("placeholder60"),
      searchClass: "search-item-width-150",
      options: vipOptions,
      allowClear: true,
    },
    {
      label: getProxyT("table7"),
      type: "select",
      model: "score_level",
      placeholder: getProxyT("placeholder60"),
      searchClass: "search-item-width-150",
      options: scoreOptions,
      allowClear: true,
    },
    {
      label: getProxyT("table6"),
      type: "select",
      model: "popular_level",
      placeholder: getProxyT("placeholder60"),
      searchClass: "search-item-width-150",
      options: popularOptions,
      allowClear: true,
    },
    {
      label: getProxyT("table4"),
      type: "select",
      model: "user_type",
      placeholder: getProxyT("placeholder62"),
      searchClass: "search-item-width-150",
      options: userTypeMap,
      allowClear: true,
    },
    {
      label: getProxyT("table3"),
      type: "select",
      model: "is_lock",
      placeholder: getProxyT("placeholder61"),
      searchClass: "search-item-width-150",
      options: lockTypeOptions,
      allowClear: true,
    },
  ],
  [
    {
      label: getProxyT("table0"),
      type: "input",
      model: "user",
      allowClear: true,
      placeholder: getProxyT("placeholder58"),
      searchClass: "search-item-width-250",
    },
    {
      label: getProxyT("table4"),
      type: "select",
      model: "user_type",
      allowClear: true,
      placeholder: getProxyT("placeholder62"),
      searchClass: "search-item-width-150",
      options: userTypeMap,
    },
    {
      label: getProxyT("table20"),
      type: "input",
      model: "origin_uid",
      allowClear: true,
      placeholder: getProxyT("placeholder63"),
    },
    {
      label: getProxyT("table21"),
      type: "input",
      model: "target_uid",
      allowClear: true,
      placeholder: getProxyT("placeholder64"),
    },
    {
      label: getProxyT("table22"),
      type: "rangePicker",
      model: "start_end",
      placeholder: computed(() => [$t("base.startTime"), $t("base.endTime")]),
      showTime: { format: "HH:mm:ss" },
      format: "YYYY-MM-DD HH:mm:ss",
    },
  ],
]);
export const defaultColumns = reactive<any>([
  [
    {
      title: getProxyT("base.index"),
      dataIndex: "index",
      key: "index",
    },
    {
      title: getProxyT("table0"),
      key: "userInfo",
    },
    {
      title: getProxyT("table1"),
      dataIndex: "age",
      key: "age",
    },
    {
      title: getProxyT("table2"),
      dataIndex: "mobile_number",
      key: "mobile_number",
    },
    {
      title: getProxyT("table3"),
      dataIndex: "is_lock",
      key: "is_lock",
    },
    {
      title: getProxyT("table4"),
      dataIndex: "account_type",
      key: "account_type",
    },
    {
      title: getProxyT("table5"),
      dataIndex: "vip_level",
      key: "vip_level",
    },
    {
      title: getProxyT("table6"),
      dataIndex: "popular_level",
      key: "popular_level",
    },
    {
      title: getProxyT("table7"),
      dataIndex: "score_level",
      key: "score_level",
    },
    {
      title: getProxyT("table8"),
      dataIndex: "conversion",
      key: "conversion",
    },
    {
      title: getProxyT("table9"),
      dataIndex: "friendNum",
      key: "friendNum",
    },
    {
      title: getProxyT("table10"),
      dataIndex: "clubNum",
      key: "clubNum",
    },
    {
      title: getProxyT("table11"),
      dataIndex: "partyNum",
      key: "partyNum",
    },
    {
      title: getProxyT("table12"),
      dataIndex: "country",
      key: "country",
    },
    {
      title: getProxyT("table13"),
      dataIndex: "channel",
      key: "channel",
    },
    {
      title: getProxyT("table14"),
      dataIndex: "merchant_user",
      key: "merchant_user",
    },
    {
      title: getProxyT("table15"),
      dataIndex: "consumeNum",
      key: "consumeNum",
    },
    {
      title: getProxyT("table16"),
      dataIndex: "consumeTotalMoney",
      key: "consumeTotalMoney",
    },
    {
      title: getProxyT("table17"),
      dataIndex: "consumeLastTime",
      key: "consumeLastTime",
      customRender: ({ text, record, index, column }: any) => {
        return getTimeByZone(text);
      },
    },
    {
      title: getProxyT("table18"),
      dataIndex: "created",
      key: "created",
      customRender: ({ text }: any) => getTimeByZone(text),
    },
    {
      title: getProxyT("table19"),
      dataIndex: "last_login_time",
      key: "last_login_time",
      customRender: ({ text }: any) => getTimeByZone(text),
    },
    {
      title: getProxyT("base.action"),
      key: "action",
    },
  ],
  [
    {
      title: getProxyT("base.index"),
      dataIndex: "index",
      key: "index",
    },
    {
      title: getProxyT("table0"),
      key: "userInfo",
    },
    {
      title: getProxyT("table2"),
      dataIndex: "mobile_number",
      key: "mobile_number",
    },
    {
      title: getProxyT("table4"),
      dataIndex: "type",
      key: "type",
    },
    {
      title: getProxyT("table20"),
      dataIndex: "origin_user",
      key: "origin_user",
    },
    {
      title: getProxyT("table21"),
      dataIndex: "target_user",
      key: "target_user",
    },
    {
      title: getProxyT("table22"),
      dataIndex: "created_at",
      key: "created_at",
      customRender: ({ text }: any) => getTimeByZone(text),
    },
    {
      title: getProxyT("table23"),
      dataIndex: "operator",
      key: "operator",
    },
  ],
]);
export let columns = reactive<IMTableType[]>([
  ...defaultColumns[tableActiveKey.value],
]);
export const defaultDrawerInputValidator = reactive<any>([
  createArray(false, 2),
  createArray(false, 4),
]);
export const isCloseDrawerVisible = ref(true);
export const subDrawerActiveKey = ref<any>(0);
export const drawer_disable_ok_button = computed(() => {
  if (operateType.value === "add") {
    if (drawerActiveKey.value === 0) {
      return (
        isEmptyType(drawerFormState.password) ||
        isEmptyType(drawerFormState.password_confirmation) ||
        isEmptyType(drawerFormState.mobile_area) ||
        isEmptyType(drawerFormState.mobile_number) ||
        defaultDrawerInputValidator[0].some((bool) => bool === true)
      );
    }
    if (drawerActiveKey.value === 1) {
      return (
        isEmptyType(drawerFormState.password) ||
        isEmptyType(drawerFormState.password_confirmation) ||
        isEmptyType(drawerFormState.mobile_number) ||
        isEmptyType(drawerFormState.nickname) ||
        isEmptyType(drawerFormState.sex) ||
        isEmptyType(drawerFormState.country_code) ||
        isEmptyType(drawerFormState.is_lock) ||
        isEmptyType(drawerFormState.mobile_area) ||
        isEmptyType(drawerFormState.birthday + "") ||
        isEmptyType(drawerFormState.avatar) ||
        (drawerFormState.sex === 1 &&
          isEmptyType(drawerFormState.month_income)) ||
        (drawerFormState.sex === 1 &&
          isEmptyType(drawerFormState.occupation_id)) ||
        isEmptyType(drawerFormState.intention) ||
        defaultDrawerInputValidator[1].some((bool) => bool === true) ||
        uploadFileLoading[0].value ||
        (drawerFormState.sex != 1 && isEmptyType(drawerFormState.height)) ||
        (drawerFormState.sex != 1 && isEmptyType(drawerFormState.weight)) ||
        isEmptyType(drawerFormState.tag_ids)
      );
    }
  }
  if (operateType.value === "update") {
    return (
      isEmptyType(drawerFormState.nickname) ||
      isEmptyType(drawerFormState.sex) ||
      isEmptyType(drawerFormState.country_code) ||
      isEmptyType(drawerFormState.is_lock) ||
      isEmptyType(drawerFormState.birthday + "") ||
      isEmptyType(drawerFormState.avatar) ||
      (drawerFormState.sex === 1 &&
        isEmptyType(drawerFormState.month_income)) ||
      (drawerFormState.sex === 1 &&
        isEmptyType(drawerFormState.occupation_id)) ||
      isEmptyType(drawerFormState.intention) ||
      defaultDrawerInputValidator[1].some((bool) => bool === true) ||
      uploadFileLoading[0].value ||
      (drawerFormState.sex != 1 && isEmptyType(drawerFormState.height)) ||
      (drawerFormState.sex != 1 && isEmptyType(drawerFormState.weight)) ||
      isEmptyType(drawerFormState.tag_ids)
    );
  }
  if (operateType.value === "view") return false;
  return true;
});
export const modal_disabled = computed(() =>
  isEmptyType(defaultModalFormState[2].location)
);
export const refreshComponent = ref(true);
export const isDisplay = ref<any>(false);
export const helpRef = ref<any>(null);
export const randomClassName = randomString();
export const modalInputValidators = reactive(
  isResetOldPassword.value ? createArray(false, 3) : createArray(false, 2)
);
export const dataRes = ref<any>({});
export const uploadFileLoading = toRefs(
  reactive<any>([false, false, false, false, false])
);
export const isShowIMH5 = ref(true);
export const scrollRef = ref<any>(null);
export const winRef = ref<any>();
export const imgTipMap = reactive({
  1: $t("dict49"),
  2: $t("dict50"),
  3: $t("dict51"),
  4: $t("dict52"),
  5: $t("dict53"),
});
export const tabPower = reactive([true, true]);
watch([() => tabPower[0], () => tabPower[1]], (newArrayState) => {
  if (newArrayState.some((item) => item === true))
    initObjAttr(columns, defaultColumns[tableActiveKey.value]);
  if (newArrayState.every((item) => item === false)) initObjAttr(columns, []);
});
